var form = layui.form,
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    element = layui.element,
    tablecols1 = [
    {checkbox: true, width:50, fixed: true}
    ,{field:'messageId', hide:true}
    ,{field:'detailId', hide:true}
    ,{field:'arrangeName', title:'安排名称', fixed: true, width:200,event:"eventName"}
    ,{field:'remindTime', title:'提醒时间', fixed: true, width:200}
    ,{field:'executionLevel', title:'执行级别', fixed: true, width:200}
    ,{field:'content', title:'内容', fixed: true}
    ,{title: "操作", templet: "#messageeditor",width:150}
    ],
    tablecols2=[
        {checkbox: true, width:50, fixed: true}
        ,{field:'messageId', hide:true}
        ,{field:'detailId', hide:true}
        ,{field:'theme', title:'主题', fixed: true, width:200,event:"eventName"}
        ,{field:'publisherName', title:'发布人', fixed: true, width:200}
        ,{field:'createTime', title:'创建时间', fixed: true, width:200}
        ,{field:'content', title:'内容', fixed: true}
        ,{title: "操作", templet: "#messageeditor",width:150}
    ],
    tablecols3 =[
        {checkbox: true, width:50, fixed: true}
        ,{field:'messageId', hide:true}
        ,{field:'detailId', hide:true}
        ,{field:'theme', title:'主题', fixed: true, width:200,event:"eventName"}
        ,{field:'contact', title:'联系人', fixed: true, width:200}
        ,{field:'remindTime', title:'提醒时间', fixed: true, width:200}
        ,{field:'content', title:'内容', fixed: true}
        ,{title: "操作", templet: "#messageeditor",width:150}
    ],
    tablecols4 =[
        {checkbox: true, width:50, fixed: true}
        ,{field:'messageId', hide:true}
        ,{field:'detailId', hide:true}
        ,{field:'theme', title:'名称', fixed: true, width:200,event:"eventName"}
        ,{field:'createName', title:'提交人', fixed: true, width:200}
        ,{field:'createTime', title:'提交时间', fixed: true, width:200}
        ,{field:'content', title:'内容', fixed: true}
        ,{title: "操作", templet: "#messageeditor",width:150}
    ],//表头
    messagetype="1"//默认消息类型
;
let arrangementNum=0;
let announcementNum=0;
let customerContactNum=0;
let pendingApprovalNum=0



element.on('nav(messagenav)', function(elem){
    if(elem.text()=="待办事项")messagetype="1",uptable(1);
    else if(elem.text()=="公告栏")messagetype="2",uptable(2);
    else if(elem.text()=="个人备忘录")messagetype="3",uptable(3);
    else if(elem.text()=="待审批事项")messagetype="4",uptable(4);
    return false;
});
//初始化表格
table.render({
    elem: '#message'
    ,type:"get"
    ,url:"messageUserDetail/selectUserMessageByPage"
    ,where:{
        "type":messagetype,
    }
    ,toolbar: '#toolbarDemo'
    ,cols: [tablecols1]
    ,id: 'messagetableid'
    ,height: $(document).height() - $('#message').offset().top - 50
    ,page: true
    ,limit: 100
    ,limits:[100, 100, 200, 300, 500, 1000]
});
//加载未读数
queryUnReadByType();

editInnerHTML();

//工具栏
table.on('toolbar(messagetable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){//批量删除
        case 'del':
            if(data.length==0){
                layer.msg("请选择要删除的数据");
                return false;
            }
            var ids = [];
            for (var i = 0;i<data.length;i++){
                ids.push(data[i].detailId)
            }
            if(delUerMessage(ids)){
                layer.msg("删除成功");
                refrash();

                editInnerHTML();
            }else{
                layer.msg("删除失败");
            }
            break;
        case 'read':
            if(data.length==0){
                layer.msg("请选择要一键已读的数据");
                return false;
            }
            var ids = [];
            for (var i = 0;i<data.length;i++){
                ids.push(data[i].detailId)
            }
            if(readUerMessage(ids)){
                layer.msg("一键已读成功");
                refrash();

                editInnerHTML();
            }else{
                layer.msg("一键已读失败");
            }
            break;

    }
});
//监听工具条
table.on('tool(messagetable)', function(obj){
    var data = obj.data;
    var ids=[];
    ids.push(data.detailId);
    if(obj.event === 'del'){
        layer.confirm('真的删除行么', function(index){
            if(delUerMessage(ids)){
                layer.msg("删除成功");
                obj.del();
                layer.close(index);

                editInnerHTML();
            }else{
                layer.msg("删除失败");
            }

        });
    }
    else if(obj.event==='read'){
        //已读
        if(readUerMessage(ids)){
            layer.msg("已读成功");
            refrash();
            editInnerHTML();
        }else{
            layer.msg("已读失败");
        }
    }
    else if(obj.event==='eventName'){
        readUerMessage(ids);
        refrash();
        editInnerHTML();

        if(messagetype == "1"){
            parent.intab("views/jsp/BasicData/tpl/viewArrangementMessage.jsp?messageId="+data.messageId,"查看待办事项详情");
        }else if(messagetype == "2"){
            parent.intab("views/jsp/BasicData/tpl/viewAnnouncementMessage.jsp?messageId="+data.messageId,"查看公告栏详情");
        }else if(messagetype == "3"){
            parent.intab("views/jsp/BasicData/tpl/viewCustomerContactMessage.jsp?messageId="+data.messageId,"查看个人备忘录详情");
        }


        return false;
    }
});

//触发事件
var active = {
    arrangement: function(){
        messagetype="1";
    }
    ,announcement: function(){
        messagetype="2";
    }
    ,customercontact: function(){
        messagetype="3";
    }
    ,pendingApproval: function(){
        messagetype="4";
    }
};

$('#messagenav .layui-nav-item a .layui-btn').on('click', function(){
    var othis = $(this), messagetype = othis.data('messagetype');
    active[messagetype] ? active[messagetype].call(this, othis) : '';
    event.stopPropagation();
});
//分页查询
function uptable(types) {
    messagetype=types;
    $("#myTable").empty();
    $("#myTable").append('<table class="layui-table" id="message" lay-filter="messagetable"></table>');
    if(types=="1"){//待办事项
        table.render({
            elem: '#message'
            ,type:"get"
            ,url:"messageUserDetail/selectUserMessageByPage"
            ,where:{
                "type":types,
            }
            ,toolbar: '#toolbarDemo'
            ,cols: [tablecols1]
            ,id: 'messagetableid'
            ,height: $(document).height() - $('#message').offset().top - 50
            ,page: true
            ,limit: 100
            ,limits:[100, 100, 200, 300, 500, 1000]
        });
    }else if(types=="2"){//公告栏
        table.render({
            elem: '#message'
            ,type:"get"
            ,url:"messageUserDetail/selectUserMessageByPage"
            ,where:{
                "type":types,
            }
            ,toolbar: '#toolbarDemo'
            ,cols: [tablecols2]
            ,id: 'messagetableid'
            ,height: $(document).height() - $('#message').offset().top - 50
            ,page: true
            ,limit: 100
            ,limits:[100, 100, 200, 300, 500, 1000]
        });
    }else if(types=="3"){
        table.render({//个人备忘录
            elem: '#message'
            ,type:"get"
            ,url:"messageUserDetail/selectUserMessageByPage"
            ,where:{
                "type":types,
            }
            ,toolbar: '#toolbarDemo'
            ,cols: [tablecols3]
            ,id: 'messagetableid'
            ,height: $(document).height() - $('#message').offset().top - 50
            ,page: true
            ,limit: 100
            ,limits:[100, 100, 200, 300, 500, 1000]
        });
    }else{
        table.render({//待审批事项
            elem: '#message'
            ,type:"get"
            ,url:"messageUserDetail/selectUserMessageByPage"
            ,where:{
                "type":types,
            }
            ,toolbar: '#toolbarDemo'
            ,cols: [tablecols4]
            ,id: 'messagetableid'
            ,height: $(document).height() - $('#message').offset().top - 50
            ,page: true
            ,limit: 100
            ,limits:[100, 100, 200, 300, 500, 1000]
        });
    }

    editInnerHTML();

}

function editInnerHTML() {
    queryUnReadByType();
    //此处再次添加 避免不加载内容
    $("#arrangement")[0].innerHTML="待办事项未读："+arrangementNum
    $("#announcement")[0].innerHTML="公告栏未读："+announcementNum
    $("#customerContact")[0].innerHTML="个人备忘录未读："+customerContactNum
    $("#pendingApproval")[0].innerHTML="待审批事项："+pendingApprovalNum
}
/**
 * 批量删除 接收人自己的消息
 * @param ids
 * @returns {boolean}
 */
function  delUerMessage(ids) {
    var tf=false;
    $.ajax({
        type : 'post',
        data:{"ids":JSON.stringify(ids)},
        url:'messageUserDetail/delUerMessage',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}

/**
 * 批量已读 接收人自己的消息
 * @param ids
 * @returns {boolean}
 */
function  readUerMessage(ids) {
    var tf=false;
    $.ajax({
        type : 'post',
        data:{"ids":JSON.stringify(ids)},
        url:'messageUserDetail/readUerMessage',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}


function refrash() {
    table.reload('messagetableid', {
        type:"get"
        ,url:"messageUserDetail/selectUserMessageByPage"
        ,where:{
            "type":messagetype,
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }
        ,limit: 100
    }, 'data');


}

function queryUnReadByType() {
    $.ajax({
        url:'message/queryUnReadByType',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                arrangementNum=da.data.arrangementNum;
                announcementNum=da.data.announcementNum;
                customerContactNum=da.data.customerContactNum;
                pendingApprovalNum=da.data.pendingApprovalNum;
            }
        }
    });
}